package com.example.yls.demoa;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements IOnDataChangeListener{


    private List<Student> studentList = new ArrayList<>();
    private StuAdapter adapter;
    private ListView listView;
    private Button add;
    private EditText searchEdit;
    private Button search;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.lv);
        add = findViewById(R.id.add);
        searchEdit = findViewById(R.id.searchEdit);
        search = findViewById(R.id.search);

        adapter = new StuAdapter(studentList,MainActivity.this,
                MainActivity.this);
        readData();
        listView.setAdapter(adapter);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,1001);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,updateActivity.class);
                intent.putExtra("STUNO",studentList.get(i).getStuno());
                intent.putExtra("NAME",studentList.get(i).getName());
                intent.putExtra("AGE",studentList.get(i).getAge());
                startActivityForResult(intent,1002);
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectData(searchEdit.getText().toString());
            }
        });

        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                selectData(searchEdit.getText().toString());
            }
        });
    }

    public void selectData(String key){
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String where = "name like '%"+key+"%' or stuno  like '%"+key+"%'  or age  like '%"+key+"%' ";
        studentList.clear();
        Cursor cursor = db.query("student",null,
                where,null,null,null,null);
        if(cursor != null && cursor.getCount() > 0){
            for (cursor.moveToFirst() ; !cursor.isAfterLast() ; cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student student = new Student(stuno,name,age);
                studentList.add(student);
            }
        }
        adapter.notifyDataSetChanged();
        cursor.close();
        db.close();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == 2001){
            String stuno = data.getStringExtra("STUNO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);

            Student student = new Student(stuno,name,age);
            addStudentToDB(student);
        }else if(resultCode == 2002){
            String stuno = data.getStringExtra("STUNO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);

            Student student = new Student(stuno,name,age);
            updateStudentToDB(student);
        }
    }

    private void updateStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        ContentValues values = new ContentValues();
        values.put("name", student.getName());
        values.put("age", student.getAge());

        String where = "stuno = '"+student.getStuno()+"'";
        db.update("student", values, where , null);
        db.close();
        readData();
    }

    private void addStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        ContentValues values = new ContentValues();
        values.put("stuno", student.getStuno());
        values.put("name", student.getName());
        values.put("age", student.getAge());

        db.insert("student", null, values);
        db.close();
        readData();
    }

    public void readData(){
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path,null);

        String sql = "create table if not exists student (stuno varchar(20), name varchar(20), age int)";
        db.execSQL(sql);

        studentList.clear();
        Cursor cursor = db.query("student",null,
                null,null,null,null,null);
        if(cursor != null && cursor.getCount() > 0){
            for (cursor.moveToFirst() ; !cursor.isAfterLast() ; cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student student = new Student(stuno,name,age);
                studentList.add(student);
            }
        }
        adapter.notifyDataSetChanged();
        cursor.close();
        db.close();
    }

    @Override
    public void delStu(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path,null);

        String sql = "delete from student where stuno = '"+student.getStuno()+"'";
        db.execSQL(sql);
        Toast.makeText(MainActivity.this,student.getName(),Toast.LENGTH_SHORT).show();
        db.close();
        readData();
    }
}
